/*---------------------------------------------------------

  SpaceBuild Gamemode

---------------------------------------------------------*/

include( 'shared.lua' )
include( 'cl_sun.lua' )
local planets = {} //Clients hasn't been updated yet

// enabled?
local Color_Enabled = false;
local Bloom_Enabled = true;
local timer = CurTime() + 0.2
local owner = 4
local planetNum = 1
local play = LocalPlayer()
local enterCheck = 1
local x = 0
local maxHealth
local max_ammo 
local worldInfo = nil
local money = 0

sb_gooniverse =
{ 
    {Index = 1, planetName = "Hiigara", Color = Color(165, 221,108,255), habitableInit = true},
	{Index = 4, planetName = "Demeter", Color = Color(0,255,0,255), habitableInit = false},
    {Index = 3, planetName = "Cerebrus", Color = Color(214,55,4,255), habitableInit = false},
	{Index = 2, planetName = "Coruscant", Color = Color(209,145,37,255), habitableInit = false},
    {Index = 6, planetName = "Kobol", Color = Color(177, 204, 255,255), habitableInit = true},
	{Index = 5, planetName = "Endgame", Color = Color(150,0,0,255), habitableInit = false},
    {Index = 7, planetName = "Sol - Outer Corona", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 8, planetName = "Sol - Inner Corona", Color = Color(255,211,0,255), habitableInit = false},
}

gm_solarsystem =
{ 
    {Index = 1, planetName = "Earth", Color = Color(165, 221,108,255), habitableInit = true},
	{Index = 2, planetName = "Moon", Color = Color(206,206,206,255), habitableInit = false},
    {Index = 3, planetName = "Mars", Color = Color(214,55,4,255), habitableInit = false},
	{Index = 4, planetName = "Venus", Color = Color(232,186,20,255), habitableInit = false},
    {Index = 5, planetName = "Mercury", Color = Color(229, 222, 176,255), habitableInit = false},
	{Index = 6, planetName = "Jupiter", Color = Color(150,0,0,255), habitableInit = false},
    {Index = 7, planetName = "Sol - Outer Corona", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 8, planetName = "Sol - Inner Corona", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 9, planetName = "Unnamed - ID: 9", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 10, planetName = "Neptune", Color = Color(59,148,211,255), habitableInit = false},
	{Index = 11, planetName = "Titan", Color = Color(211,211,211,255), habitableInit = false},
}

gm_dominionwars =
{ 
    {Index = 1, planetName = "Earth", Color = Color(165, 221,108,255), habitableInit = true},
	{Index = 2, planetName = "Moon", Color = Color(206,206,206,255), habitableInit = false},
    {Index = 3, planetName = "Mars", Color = Color(214,55,4,255), habitableInit = false},
	{Index = 4, planetName = "Hayabaya", Color = Color(165, 221,108,255), habitableInit = false},
    {Index = 5, planetName = "Mercury", Color = Color(229, 222, 176,255), habitableInit = false},
	{Index = 6, planetName = "Jupiter", Color = Color(150,0,0,255), habitableInit = false},
    {Index = 7, planetName = "Sol - Outer Corona", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 8, planetName = "Sol - Inner Corona", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 9, planetName = "Unnamed - ID: 9", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 10, planetName = "Neptune", Color = Color(59,148,211,255), habitableInit = false},
	{Index = 11, planetName = "Titan", Color = Color(211,211,211,255), habitableInit = false},
}

gm_new_worlds =
{ 
    {Index = 1, planetName = "Earth Hanger", Color = Color(165, 221,108,255), habitableInit = true},
	{Index = 4, planetName = "Moon", Color = Color(206,206,206,255), habitableInit = false},
    {Index = 3, planetName = "Barren Planet", Color = Color(214,55,4,255), habitableInit = false},
	{Index = 2, planetName = "Toxic Planet", Color = Color(120,135,23,255), habitableInit = false},
    {Index = 6, planetName = "Desert Planet", Color = Color(229, 222, 176,255), habitableInit = false},
	{Index = 5, planetName = "Arctic Moon", Color = Color(211,211,211,255), habitableInit = false},
    {Index = 7, planetName = "Unamed - ID 7", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 8, planetName = "Aquacia", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 9, planetName = "Asteroid Station", Color = Color(0,131,193,255), habitableInit = false},
	{Index = 10, planetName = "Neptune", Color = Color(59,148,211,255), habitableInit = false},
	{Index = 11, planetName = "Titan", Color = Color(211,211,211,255), habitableInit = false},
}

gm_spacewar =
{ 
    {Index = 1, planetName = "Radia", Color = Color(67, 255,0,255), habitableInit = true},
	{Index = 4, planetName = "Arashi", Color = Color(165, 221,108,255), habitableInit = false},
    {Index = 3, planetName = "Hotmar", Color = Color(214,55,4,255), habitableInit = false},
	{Index = 2, planetName = "Anu", Color = Color(0,70,255,255), habitableInit = false},
    {Index = 5, planetName = "Igom", Color = Color(0, 25, 255,255), habitableInit = false},
	{Index = 6, planetName = "Sol - Outer Corona", Color = Color(255,211,0,255), habitableInit = false},
    {Index = 7, planetName = "Sol - Inner Corona", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 8, planetName = "Sol - Core", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 9, planetName = "Luna", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 10, planetName = "The Room", Color = Color(0,0,200,255), habitableInit = false},
	{Index = 11, planetName = "Chinook", Color = Color(121,64,16,255), habitableInit = false},
	{Index = 12, planetName = "Spawn Station", Color = Color(211,211,211,255), habitableInit = false},
}

gm_galactic =
{ 
    {Index = 1, planetName = "O42 - Teleporter Room", Color = Color(165, 221,108,255), habitableInit = true},
	{Index = 4, planetName = "O42 - Hull", Color = Color(206,206,206,255), habitableInit = false},
    {Index = 3, planetName = "Caementum", Color = Color(214,55,4,255), habitableInit = false},
	{Index = 2, planetName = "Aquosus", Color = Color(0,186,211,255), habitableInit = false},
    {Index = 6, planetName = "Shell - Galactic Sevice Station", Color = Color(255, 222, 0,255), habitableInit = false},
	{Index = 5, planetName = "Ignius", Color = Color(150,0,0,255), habitableInit = false},
    {Index = 7, planetName = "Aureoreta", Color = Color(255,211,0,255), habitableInit = false},
	{Index = 8, planetName = "Noxis", Color = Color(150,150,50,255), habitableInit = false},
	{Index = 9, planetName = "Ultimus", Color = Color(255,211,0,255), habitableInit = false},
}

local ColorModify = {                // Color Variables.
	[ "$pp_colour_addr" ] = 0,
	[ "$pp_colour_addg" ] = 0,
	[ "$pp_colour_addb" ] = 0,
	[ "$pp_colour_brightness" ] = 0,
	[ "$pp_colour_contrast" ] = 0,
	[ "$pp_colour_colour" ] = 0,
	[ "$pp_colour_mulr" ] = 0,
	[ "$pp_colour_mulg" ] = 0,
	[ "$pp_colour_mulb" ] = 0,
};

local Bloom = {                        // Bloom Variables
	darken = 0,
	multiplay = 0,
	sizex = 0,
	sizey = 0,
	passes = 0,
	color = 0,
	col = {
		r = 0,
		g = 0,
		b = 0,
	},
};

local function SetColor(planet)
	// don't support colormod?
	if( !render.SupportsPixelShaders_2_0() ) then return; end
	// enabled?
	Color_Enabled = planet.color
	if( !Color_Enabled ) then return; end
	// read attributes
	ColorModify[ "$pp_colour_addr" ] 	= planet.AddColor_r
	ColorModify[ "$pp_colour_addg" ] 	= planet.AddColor_g
	ColorModify[ "$pp_colour_addb" ] 	= planet.AddColor_b
	ColorModify[ "$pp_colour_brightness" ] 	= planet.Brightness
	ColorModify[ "$pp_colour_contrast" ] 	= planet.Contrast
	ColorModify[ "$pp_colour_colour" ] 	= planet.CColor
	ColorModify[ "$pp_colour_mulr" ] 	= planet.AddColor_r
	ColorModify[ "$pp_colour_mulg" ] 	= planet.AddColor_g
	ColorModify[ "$pp_colour_mulb" ] 	= planet.AddColor_b
end

local function SetBloom(planet)
	// don't support bloom?
	if( !render.SupportsPixelShaders_2_0() ) then return; end
	// enabled?
	Bloom_Enabled = planet.bloom
	if( !Bloom_Enabled ) then return; end
	// read attributes
	Bloom.darken 	= planet.Darken
	Bloom.multiplay 	= planet.Multiplay
	Bloom.sizex 	= planet.SizeX
	Bloom.sizey 	= planet.SizeY
	Bloom.passes 	= planet.Passes
	Bloom.color 	= planet.BColor
	Bloom.col.r 	= planet.Col_r
	Bloom.col.g 	= planet.Col_g
	Bloom.col.b 	= planet.Col_b
end

local function Render( )
	if( Color_Enabled ) then
		// draw colormod.
		DrawColorModify( ColorModify );
	end
	if( Bloom_Enabled ) then
		// draw bloom.
		DrawBloom(
			Bloom.darken, 
			Bloom.multiplay, 
			Bloom.sizex, Bloom.sizey, 
			Bloom.passes, 
			Bloom.color, 
			Bloom.col.r, 
			Bloom.col.g, 
			Bloom.col.b 
		);
	end
end

local function recPlanet( msg )
	local hash  = {}
	hash.pos = msg:ReadVector();
	hash.radius = msg:ReadFloat();
	hash.num = msg:ReadShort()
	if msg:ReadBool() then
		hash.color = true
		hash.AddColor_r = msg:ReadShort()
		hash.AddColor_g = msg:ReadShort()
		hash.AddColor_b = msg:ReadShort()
		hash.MulColor_r = msg:ReadShort()		
		hash.MulColor_g = msg:ReadShort()
		hash.MulColor_b = msg:ReadShort()
		hash.Brightness = msg:ReadFloat()
		hash.Contrast = msg:ReadFloat()
		hash.CColor = msg:ReadFloat()
	else
		hash.color = false
	end
	if msg:ReadBool() then
		hash.bloom = true
		hash.Col_r = msg:ReadShort()
		hash.Col_g = msg:ReadShort()
		hash.Col_b = msg:ReadShort()
		hash.SizeX = msg:ReadFloat()
		hash.SizeY = msg:ReadFloat()
		hash.Passes = msg:ReadFloat()
		hash.Darken = msg:ReadFloat()
		hash.Multiplay = msg:ReadFloat()
		hash.BColor = msg:ReadFloat()
	else
		hash.bloom = false
	end
	planets[ hash.num ] = hash
end

function GM:Space_Affect_Cl ()
	local play = LocalPlayer()
	if not (play and play:IsValid() and play:Alive()) then return end
	local ppos = play:GetPos()
	for _, p in pairs( planets ) do
		if ppos:Distance(p.pos) < p.radius then
			if not (play.planet == p.num) then
				SetBloom(p)
				SetColor(p)
				play.planet = p.num
		  	end
			return
		end
	end
	if (play.planet != 0) then
		Color_Enabled = false
		Bloom_Enabled = false
		play.planet = 0
	end
end

function GM:Think()
	if (GetGlobalInt("InSpace") == 0) then return end
	if timer > CurTime() then return end
	self:Space_Affect_Cl()
	timer = CurTime() + 1
customHUD(LocalPlayer())
end

function Scores(close) 
	local DermaPanel = vgui.Create( "DFrame" )
	DermaPanel:SetPos( 50,50 )
	DermaPanel:SetSize( 330, 350 )
	DermaPanel:SetTitle( " =====================Score Panel===================" )
	DermaPanel:SetVisible( true )
	DermaPanel:SetDraggable( true )
	DermaPanel:ShowCloseButton( true )
	DermaPanel:MakePopup()
	
	local PropertySheet = vgui.Create( "DPropertySheet" )
	PropertySheet:SetParent( DermaPanel )
	PropertySheet:SetPos( 0, 25 )
	PropertySheet:SetSize( 290, 325 )

	
	local playerStats = vgui.Create("DListView")
	playerStats:SetParent(DermaPanel)
	playerStats:SizeToContents()
	playerStats:SetMultiSelect(false)
	playerStats:AddColumn("Name") // Add column
	playerStats:AddColumn("Team")
	playerStats:AddColumn("Score")
	playerStats:AddColumn("Cash")
	for k,v in pairs(player.GetAll()) do
	playerStats:AddLine(v:Nick(), All_Teams[v:Team()].Name, v:Frags(), tostring(v.money)) // Add lines
	end


	local teamStats = vgui.Create("DListView")
	teamStats:SetParent(DermaPanel)
	teamStats:SizeToContents()
	teamStats:SetMultiSelect(false)
	teamStats:AddColumn("Name") // Add column
	teamStats:AddColumn("Score")
	teamStats:AddColumn("Cash")
	teamStats:AddColumn("Territory")
	for k,v in pairs(All_Teams) do
		local frags = 0
		local cash = 0
		if(v.Index != 4) then
			for m,play in pairs(player.GetAll()) do
				if(play:Team() == v.Index) then
					frags = frags + play:Frags()
					cash = cash + money
				end
			end
		end
		teamStats:AddLine(v.Name, frags, cash) // Add lines
	end


	PropertySheet:AddSheet( "player Scores", playerStats, "gui/silkicons/user", false, false, "This is the individual scores for each player." )
	PropertySheet:AddSheet( "Planetary Ownership", teamStats, "gui/silkicons/group", false, false, "This is the planetary control ratios" ) 
	
end

function teamsPanel() // Create the function
	local play = LocalPlayer()
	panel = vgui.Create("DFrame") // Create the frame
	menu1 = vgui.Create("DButton") // Create the button
	panel:SetPos((ScrW()/2) -100, (ScrH()/2) - 50) // set the frame's position on the screen
	panel:SetSize(200, 100) // set the frame size
	panel:SetTitle( "Choose your Side" ) // set the frame title
	panel:SetVisible( true ) // Make the frame visible
	panel:MakePopup() // make the frame popup
	panel:ShowCloseButton( false )  // make the frame popup
	menu1:SetParent( panel ) // parent the button to the frame
	menu1:SetText( "Decide Your Allegence" ) // set the button text
	menu1:SetPos(25, 50) // set the button position in the frame
	menu1:SetSize( 150, 20 ) // set the button size
	menu1.DoClick = function ( btn ) // this will be called when the button is clicked
		local menu123 = DermaMenu() // create a derma menu
		menu123:AddOption("Terran Dominion", function() play:ConCommand("say /join TD")  panel:SetVisible( false )  end ) // adding options
		menu123:AddOption("Xenophire Empire", function() play:ConCommand("say /join XE") panel:SetVisible( false )   end )
		menu123:AddOption("Arbiter", function() play:ConCommand("say /join AA") panel:SetVisible( false )   end)
		menu123:Open() 
	end // ending the doclick function
end // ending the function

function customHUD(play)
//Health HUD
if pcall(function() 
	


	if(play == nil) then
		play = LocalPlayer()
	end
	
	local healthRatio = 200 / maxHealth
	local tempHealth = 100/ maxHealth
	local health = tempHealth*play:Health()
	local alive = play:Alive()

--Health Bar
	draw.RoundedBox( 1, 75, ScrH() -  50, 200, 15, Color(174, 141, 14, 100) ) 
	draw.RoundedBox( 1, 75, ScrH() -  50, healthRatio*play:Health(), 15, Color(150, 211, 64, 100) ) 
	draw.SimpleText("Health:", "ScoreboardText",  50, ScrH() -  43, Color(244, 187, 63, 255), 1, 1)
	draw.SimpleText(health.."%", "ScoreboardText",  180, ScrH() -  43, Color(0, 0, 0, 255), 1, 1)
--Armor Bar		
	draw.RoundedBox( 1, 75, ScrH() -  30, 200, 15, Color(174, 141, 14, 100) ) 
	draw.RoundedBox( 1, 75, ScrH() -  30, (play:Armor()*2), 15, Color(23, 143, 229, 100) ) 
	draw.SimpleText("Armor:", "ScoreboardText",  50, ScrH() -  23, Color(244, 187, 63, 255), 1, 1)
	draw.SimpleText(tostring(play:Armor()).."%", "ScoreboardText",  180, ScrH() -  23, Color(0, 0, 0, 255), 1, 1)
	
--Ammo Bar	
	


local alive = play:Alive()

		if(play:Team() == 1) then
			 max_ammo = 30
		elseif(play:Team() == 2) then
			 max_ammo = 100 
		elseif(play:Team() == 3) then
			 max_ammo = 100
		end

			local clip = play:GetActiveWeapon():Clip1()
			local mag_extra = play:GetAmmoCount(play:GetActiveWeapon():GetPrimaryAmmoType()) 
			local secondary_ammo = play:GetAmmoCount(play:GetActiveWeapon():GetSecondaryAmmoType())
			local size = (300 / max_ammo )
			clip = play:GetActiveWeapon():Clip1()
			if(clip < 0) then clip = mag_extra  end
			

			//print(size)
			draw.RoundedBox( 1, (ScrW()-35), (ScrH() -50) - (clip*size), 30, (clip*size), Color(255, 0, 0, 100) ) 
			//draw.RoundedBox( 1, 75, ScrH() -  30, 300, 15, Color(23, 143, 229, 100) ) 
		
if(string.sub(clip, 3, 3) != nil) then
	draw.SimpleText(string.sub(clip, 3,3 ), "ScoreboardText", (ScrW()-20), (ScrH()-20) - (clip*size), Color(0, 0, 0, 255), 1, 1)
end
draw.SimpleText(string.sub(clip, 2,2 ), "ScoreboardText", (ScrW()-20), (ScrH()-32) - (clip*size), Color(0, 0, 0, 255), 1, 1)

draw.SimpleText(string.sub(clip, 1,1 ), "ScoreboardText", (ScrW()-20),  (ScrH()-44) - (clip*size), Color(0, 0, 0, 255), 1, 1)
			//print(clip, mag_extra,secondary_ammo)

end) then
end	
	
//Planet HUD
if pcall(function() 
	if(valid == "true") then
		if (string.sub(GetMap(), 1,14 ) == "gm_solarsystem") then
			world = gm_solarsystem
		elseif(GetMap() == "sb_gooniverse") then
			world = sb_gooniverse
		elseif(GetMap() == "gm_new_worlds") then
			world = gm_new_worlds
		elseif(string.sub(GetMap(), 1,11 ) == "gm_Spacewar") then
			world = gm_spacewar
		elseif(string.sub(GetMap(), 1,11 ) == "GM_Galactic") then
			world = gm_galactic
		elseif(string.sub(GetMap(), 1,15 ) == "gm_dominionwars") then
			world = gm_dominionwars
		end
		
	    if not file.Exists("DominionWars/"..GetMap()..".txt") then
			file.Write("DominionWars/"..GetMap()..".txt", util.TableToKeyValues(world))
		end
		
		
		local contents = file.Read("DominionWars/"..GetMap()..".txt")
			
		 
	
		 
	//worldInfo = nil
		if(worldInfo == nil) then
			worldInfo = util.KeyValuesToTable(contents)
		else
					worldInfo = util.KeyValuesToTable(contents)
			planetInfo = worldInfo[tostring(planetNum)]
			planetColor = planetInfo["color"]
			
			draw.RoundedBox( 8, ScrW() - 203, ScrH() - (ScrH() - 26), 200, 80, Color(50,50,75,150) ) 
			draw.SimpleText(tostring(planetInfo["planetname"]), "ScoreboardText",  ScrW() - 100, 37, Color(planetColor["r"],planetColor["g"],planetColor["b"],255),1,1)
			draw.SimpleText("-------------Owner-------------", "ScoreboardText",  ScrW() - 103, 78, Color(255,255,255,255),1,1) 
			draw.SimpleText(All_Teams[tonumber(owner)].Name, "ScoreboardText",  ScrW() - 103, 93, All_Teams[tonumber(owner)].Color,1,1) 
			
							LocalPlayer():PrintMessage( HUD_PRINTCHAT , All_Teams[tonumber(owner)].territoryHail)

			if(owner != 4 and enterCheck == 0)then
				LocalPlayer():PrintMessage(HUD_PRINTTALK , All_Teams[tonumber(owner)].territoryHail)
				enterCheck = 10
			end
			
			if(owner == 4 and enterCheck == 0) then
				LocalPlayer():PrintMessage(HUD_PRINTTALK , "Welcome to Conflict Zone: \""..planetInfo["planetname"].."\"")
				enterCheck = 10
				
			end
			
		end
		
	else
		enterCheck = 0
		
		
	end
end) then
end	
	
//Wallet HUD
if pcall(function() 
	moneyRatio = 200/5000
	walletWidth = moneyRatio * money
	draw.RoundedBox( 1, 75, ScrH() -  70, 200, 15, Color(174, 141, 14, 100) ) 
	if(money > 0) then
		draw.RoundedBox( 1, 75, ScrH() -  70, walletWidth, 15, Color(229, 215, 16, 100)) 
	end
	draw.SimpleText("$"..(tostring(money)), "ScoreboardText",  175, ScrH() -  63, Color(0, 0, 0, 255), 1, 1)
end) then
end
end

function hidehud(name)
	for k, v in pairs{"CHudHealth", "CHudBattery", "CHudAmmo", "CHudSecondaryAmmo"} do
		if name == v then return false end
	end
end

function GetMap()
	local worldspawn = ents.GetByIndex(0)
	local mapname = worldspawn:GetModel()
  
	mapname = string.gsub(mapname,"(%w*/)","")
	mapname = string.gsub(mapname,".bsp","")
   
	return mapname
 end 
 
function planetValid_HUD( um )
	valid = um:ReadString()
end
 
function playerMaxHealth( um )
	maxHealth =  um:ReadLong()
	//print("Max Health:", maxHealth)
end

function planetOwner_HUD( um )
	owner = um:ReadLong()
end

function planetNumber_HUD( um )
	planetNum = um:ReadLong()
	//print(planetNum)
end

function moneyHUD( um )
	money = um:ReadLong()
	print(money)
end




				/***************************************************************************************************/
				/**********************************This is the Gamemode HOOKS section*********************************/
				/***************************************************************************************************/
concommand.Add("score",Scores, close) // adding the console command 
concommand.Add("join",teamsPanel) // adding the console command 
usermessage.Hook("money", moneyHUD) 
usermessage.Hook("planetNumber_HUD", planetNumber_HUD) 
usermessage.Hook("planetOwner_HUD", planetOwner_HUD) 
usermessage.Hook("playerMaxHealth", playerMaxHealth) 
usermessage.Hook("planetValid_HUD", planetValid_HUD) 
usermessage.Hook( "AddPlanet", recPlanet );
hook.Add( "RenderScreenspaceEffects", "VFX_Render", Render );
hook.Add("HUDPaint", "planetHUD", customHUD)
hook.Add("HUDShouldDraw", "hidehud", hidehud) 
